<!-- 部门管理 部门列表组件 -->
<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryInfo.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="queryInfo.status" placeholder="状态" clearable style="width: 240px">
            <el-option label="正常" value="0">正常</el-option>
            <el-option label="停用" value="1">停用</el-option>
          </el-select>
                  </el-form-item> -->
        <el-form-item label="权限标识" prop="roleKey">
          <el-input v-model="queryInfo.roleKey" placeholder="请输入权限标识" clearable />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTimeOpen">
          <el-date-picker v-model="value1" value-format="yyyy-MM-dd hh:mm:ss" style=" width:240px" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTypeHandle">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="success" plain icon="el-icon-edit" size="mini">修改</el-button> -->
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="danger" plain icon="el-icon-delete" size="mini">删除</el-button> -->
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="warning" plain icon="el-icon-download" size="mini">导出</el-button> -->
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%;margin-bottom: 20px;" row-key="id" default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="roleId" label="角色编号">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleKey" label="权限字符">
        </el-table-column>
        <el-table-column prop="roleSort" label="显示顺序">
        </el-table-column>
         <el-table-column prop="remark" label="备注">
          </el-table-column>
        <el-table-column label="状态" align="center" key="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
              @change="userStateChanged(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="editHandler(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteDeptHandle(scope.row)">删除</el-button>
            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item size="mini" type="text" icon="el-icon-user"
                  command="userDataView">分配用户</el-dropdown-item>
                <el-dropdown-item size="mini" type="text" icon="el-icon-circle-check"
                  command="dataRouleHander">数据权限</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加 弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" @close="addDialogClosed">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限" >
          <!-- <el-button type="primary" size="mini" @click="expand">展开/折叠</el-button>
          <el-button type="primary" size="mini" @click="checkAll">全选</el-button>
          <el-button type="primary" size="mini" @click="checkNot">全不选</el-button> -->
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
              <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <div class="menuBox">
            <el-tree :default-checked-keys="defaultList" check-on-click-node :default-expand-all="expandNode"
              class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="menuId" empty-text="加载中，请稍候"
              :check-strictly="!form.menuCheckStrictly" :props="defaultProps"></el-tree>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">下一步</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    <!-- <div class="buttons">
        <el-button @click="getMenuAllCheckedKeys">通过 node 获取</el-button>
                </div> -->
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog title="数据权限表" :visible.sync="openDataScope" width="1100px" append-to-body :before-close="cancelDataScope">
      <el-dialog
        width="30%"
        title="自定义权限角色"
        :visible.sync="innerVisible"
        append-to-body
        :before-close="handleClose"
        >
        <el-tree
        ref="tree"
        :data="treeData"
        :props="treeProps"
        node-key="id"
        :default-expanded-keys="[1]"
        :check-strictly="false"
        show-checkbox
        @check="handleCheckChange"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openCustom">确 定</el-button>
        <el-button @click="closedCustom">取 消</el-button>
      </div>
      </el-dialog>
      <div>
        <el-alert
        title="注：有多个角色对应的数据范围存在分歧时以范围大的为准！"
        style="margin-bottom: 20px;"
        type="warning">
      </el-alert>
      <ul class="dialog-table">
        <div style="display: flex;">
          <div>
            <input type="text" style="width:180px; height:24px; paddingLeft:20px" v-model="condition">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="hanldeCheckedNewDataScope">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="hanldeCheckedReset">重置</el-button>
          </div>
          <div class="top-radio">
            <div>数据范围</div>
            <el-radio-group v-model="radiofanwei" style="margin-left: 24px;">
              <el-radio label="1" @change="handleCheckedRadio('1')">全部</el-radio>
              <el-radio label="5" @change="handleCheckedRadio('5')">仅自己</el-radio>
              <el-radio label="3" @change="handleCheckedRadio('3')">所属组织</el-radio>
              <el-radio label="4" @change="handleCheckedRadio('4')">所属组织及以下</el-radio>
            </el-radio-group>
          </div>
        </div>
        <li v-for="(item,index) in dataScopeList" :key="index">
            <div style="width: 400px;">
              {{ item.uri }}&nbsp;[{{ item.describe}}]
            </div>
            <div>
              <el-radio-group v-model=item.dataScope>
              <el-radio v-model=item.dataScope label="1">全部</el-radio>
              <el-radio v-model=item.dataScope label="5">仅自己</el-radio>
              <el-radio v-model=item.dataScope label="3">所属组织</el-radio>
              <el-radio v-model=item.dataScope label="4">所属组织及以下</el-radio>
              <el-radio v-model=item.dataScope label="2">自定义</el-radio>
            </el-radio-group>
            </div>
            <div v-if="item.dataScope=='2'" style="width: 80px;color:rgb(64,158,255);cursor: pointer;"  @click="openCustomizer(index)">
              选择组织
            </div>
              <div v-if="item.dataScope!='2'" style="width: 80px;"></div>
        </li>
      </ul>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">下一步</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    // 验证邮箱的规则 自定义校验规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱!'))
    }
    // 验证手机的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的规则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号!'))

    }
    return {
      defaultList: [], // 修改菜单回显默认选中
      value1: [],
      // 部门列表
      deptOptions: [],
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      dProps: {
        children: "child",
        label: "name"
      },
      result: [],
      // 弹出层标题
      title: "",
      isClose:false,
      newRowid:undefined,
      currentPage: 1,
      showSearch: true,
      roleKey: undefined,
      roleName: undefined,
      roleIds: undefined,
      // 表单参数
      form: {
        status: '0',
        dataScope:'',
      },
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 获取用户列表数据的参数对象 // 查询参数
      queryInfo: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        roleName: undefined, // 角色名称
        status: undefined, // 状态
        createTimeOpen: undefined, // 创建时间
        createTimeClose: undefined, // 结束时间
        roleKey: undefined // 权限标识
      },
      expandNode: false,
      userList: [],
      total: 0,
      // 对话框显示与隐藏
      dialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        roleName: '',
        act: '',
        roleSort: '',
        roleKey: '',
        status: '0',
        remark: '',
      },
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 添加表单验证的校验规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名!', trigger: 'blur', },
          { min: 3, max: 12, message: '用户名的长度在3~12个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码!', trigger: 'blur', },
          { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱!', trigger: 'blur', },
          { validator: checkEmail, trigger: 'blur', }
        ],
        mobile: [
          { required: true, message: '请输入手机号!', trigger: 'blur', },
          { validator: checkMobile, trigger: 'blur', }
        ],
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      dataScopeList: [],//永远展示的数据
      newdataScopeList: [],//过度用
      formScope: [],//过度用
      condition:'', //搜索的参数
      radiofanwei:'', //单选框的全选选项
      innerVisible:false,
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      treeindex:0,
      checkId:[], //选中的id
    }
  },
  // 计算属性
  computed: {},
  created() {
    this.getList()
    // this.handleSizeChange()
    // this.handleCurrentChange()
    this.getMenuList()
  },
  mounted() { },
  // 组件方法
  methods: {
    async handleClose(){
      this.$refs.tree.setCheckedKeys([])
      this.innerVisible=false
    },
    //点击数据权限的搜索按钮
    async hanldeCheckedNewDataScope(){
      // 类似{...this.formScope,...this.dataScopeList} 实现这个数组合并
      const newArr = this.formScope.map(obj => {
      const matchingObject = this.dataScopeList.find(item => item.uri === obj.uri);
      return matchingObject ? { ...obj, dataScope: matchingObject.dataScope } : obj;
    });
    //最终合并的数组为newArray
    const newArray = newArr.concat(this.dataScopeList.filter(obj => !this.formScope.some(item => item.uri === obj.uri)));
      const { data: res } = await this.$http.get('/sys-role-scope-dtp/apis',{
        params: {
          roleKey: this.roleKey,
          condition:this.condition
        }
      })
      if (res.code === 20000) {
        const arr = newArr.filter(itemA => res.data.some(itemB => itemB.uri === itemA.uri));
        this.newdataScopeList=newArray
        this.dataScopeList=arr
      } else {
        this.$message.error(res.msg)
      }
    },
    //点击重置
    async hanldeCheckedReset(){
      this.radiofanwei=''
      this.condition=''
      //用相同的方法把this.newdataScopeList和this.dataScopeList 赋值给this.dataScopeList
      const newArr = this.newdataScopeList.map(obj => {
        const matchingObject = this.dataScopeList.find(item => item.uri === obj.uri);
        return matchingObject ? { ...obj, dataScope: matchingObject.dataScope } : obj;
      });
      const newArray = newArr.concat(this.dataScopeList.filter(obj => !this.newdataScopeList.some(item => item.uri === obj.uri)));
      this.dataScopeList=newArray
    },
    //打开选择组织的弹窗
    async openCustomizer(index){
      //数据处理
      function convertToTreeData(data) {
        const treeData = [];

        function convert(dept) {
          const node = {
            id: dept.deptId,
            label: dept.deptName,
            children: []
          };

          if (dept.children && dept.children.length > 0) {
            dept.children.forEach(child => {
              node.children.push(convert(child));
            });
          }

          return node;
        }

      data.forEach(root => {
        treeData.push(convert(root));
      });
      return treeData;
      }
        this.innerVisible=true
        const { data: res } = await this.$http.post('/sys-dept/page',{})
        if (res.code === 20000) {
          const Data = convertToTreeData(res.data);
          this.treeData=Data
        } else {
          this.$message.error(res.msg)
        }
        this.treeindex=index
      //将tree的默认选中的id展示为dataScopeList[index].deptIds
      // this.$refs.tree.setCheckedKeys()
      if(this.dataScopeList[index]&&('depIds' in this.dataScopeList[index])){
          this.$refs.tree.setCheckedKeys(this.dataScopeList[index].depIds)
      }
    },
    //树的选择框
    handleCheckChange(data) {
      console.log(data);
        // this.checkId=data.id
      },
    //全部选中
    handleCheckedRadio(type){
      this.radiofanwei=type
      this.dataScopeList.forEach(item => {
        item.dataScope = type
      })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'userDataView':
          this.userDataView(row)
          break
        case 'dataRouleHander':
          this.dataRouleHander(row)
          break
        default:
          break
      }
    },
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
        this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
    },
    // 角色列表
    async getList() {
        this.queryInfo.createTimeOpen = this.value1[0]
        this.queryInfo.createTimeClose = this.value1[1]
        const { data: res } = await this.$http.post('/sys-role/page', (this.queryInfo))
        if (res.code === 20000) {
          this.userList = res.data.records
          this.total = parseInt(res.data.total)
        }
    },
    // 删除
    // async deleteDeptHandle(row) {
    //   console.log(row);
    //   const { data: res } = await this.$http.post('/sys-role/delete',
    //     [row.roleId]
    //   )
    //   if (res.code === 20000) {
    //     this.getList();
    //     this.$message.success('删除成功!')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
    // 删除弹窗封装
    async deleteDeptHandle(row) {
      if (!(await this._box(row.roleId, 'post', '/sys-role/delete', 'scopeId'))) return;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // console.log(this.value1);
      this.queryInfo.currentPage = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.value1 = []
      this.$refs.queryForm.resetFields()
      this.handleQuery();
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs.form.resetFields()
    },
    // 新增 弹窗
    addTypeHandle() {
      this.reset();
      this.dialogVisible = true
      this.title = "添加角色"
    },
    // getCheckedIds(data, result) {
    //   result = result || []; // 初始化结果数组
    //   for (var i = 0; i < data.length; i++) {
    //     var node = data[i];
    //     if (node.checked) {
    //       result.push(node.id);
    //     }
    //     if (node.children) {
    //       getCheckedIds(node.children, result);
    //     }
    //   }
    //   return result;
    // }, 

    // 这个函数接受两个参数，第一个参数是数据数组，第二个参数是可选的结果数组，用于存储所有被选中的节点的 ID。
    // 如果未传入结果数组，则默认初始化为空数组。
    // 函数通过遍历数据数组中的每个节点来查找被选中的节点。
    // 如果当前节点被选中，将其 ID 添加到结果数组中。
    // 如果当前节点有子节点，则递归调用 getCheckedIds 函数来遍历其子节点。
    // 函数返回结果数组，其中包含所有被选中的节点的 ID。   尼

    findCheckedId(data, result) {
      data.forEach((item) => {
        if (item.checked === true) {
          result.push(item.id);
        }
        if (item.child && item.child.length > 0) {
          this.findCheckedId(item.child, result) // 递归遍历查找子集中的checked为true的id
        }
      })
    },  // 递归 菜单树数据 拿到所有 checked 为 true 的 id
    // 修改 弹窗
    async editHandler(row) {
      this.reset();
      const roleId = row.roleId || this.ids
      const { data: res } = await this.$http.get(`/sys-role/roleMenuTreeData?roleId=${roleId}`)
      if (res.code === 20000) {
        console.log(res);
        let result = []
        this.findCheckedId(res.data, result)
        console.log(result);
        this.defaultList = result // 赋值选中按钮
        // let arr = []
        // res.data.forEach(element => {
        //   console.log(element.id);
        //     arr.push(element.id)
        //   if (element.child) {
        //     console.log(element.child);
        //     element.child.forEach(item => {
        //       console.log(item.id);
        //       arr.push(item.id)
        //     })
        //   }
        // })
        // this.defaultList = arr
        // this.defaultList = res.data[0].id
        // checkedKeys.forEach((v) => {
        //       this.$nextTick(()=>{
        //           this.$refs.menu.setCurrentKey(v, true ,false);
        //       })
        //   })
      }
      this.dialogVisible = true
      this.title = "修改角色"
      this.form = {
        ...row,
      }
    },
    /** 根据角色ID查询菜单树结构 */

    async getRoleMenuTreeselect(roleId) {

    },
    // 点击分配用户 跳转页面
    userDataView(row) {
      this.$router.push({ path: '/userRoule', query: { roleId: row.roleId } })
    },
    // 数据权限
    async dataRouleHander(row) {
      this.roleName = row.roleName
      this.roleKey = row.roleKey
      this.roleIds = row.roleId
      this.openDataScope = true;
      this.form.dataScope = row.dataScope
      // const { data: res } = await this.$http.get(`/sys-role/catRoleDataScope?roleId=${row.roleId}`, (this.queryInfo))
      // if (res.code === 20000) {
      //   // this.form = response.data;
      //   this.deptOptions = res.data
      // } else {
      //   this.$message.error(res.msg)
      // }
      const { data: res } = await this.$http.get('/sys-role-scope-dtp/apis',{
        params: {
          roleKey: row.roleKey
        }
      })
      if (res.code === 20000) {
        this.dataScopeList = res.data
        this.formScope = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getList()
    },
    // 监听 switch 开关的状态
    async userStateChanged(row) {
      // console.log(row.status)
      const params = {
        status: row.status,
        roleId: row.roleId.toString(),
        version: row.version,
      }
      const { data: res } = await this.$http.get('/sys-role/updateStatus', {
        params,
      })
      if (res.code === 20000) {
        // this.queryInfo.state = row.state
        // row.status = row.status === true ? "1" : "0";
        return this.$message.success('更新状态成功!')
      } else {
         //如果请求失败，将状态还原
        row.status = !row.status
        this.$message.error(res.msg)
      }
    },
    // 所有菜单节点数据
    // getMenuAllCheckedKeys() {
    //   // 目前被选中的菜单节点
    //   let checkedKeys = this.$refs.menu.getCheckedKeys();
    //   console.log(checkedKeys);
    //   // 半选中的菜单节点
    //   let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
    //   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    //   console.log(checkedKeys);
    //   return checkedKeys;
    // },
    expand() { // 展开/折叠
      this.isExpand = !this.isExpand
      const nodes = this.$refs.menu.store._getAllNodes()
      for (let i in nodes) {
        nodes[i].expanded = this.isExpand
      }
    },
    checkAll() { // 全选
      this.$refs.menu.setCheckedNodes(this.menuOptions)
    },
    checkNot() { // 全不选
      this.$refs.menu.setCheckedKeys([])
    },
    toggleEltree() {
      this.expandNode = !this.expandNode
      let allNodes = this.$refs.elTree.store.nodesMap;
      for (let x in allNodes) {
        allNodes[x].expanded = this.expandNode;
      }
    },
    getMenuAllCheckedKeys() {
      // console.log(this.$refs.menu.getCheckedNodes());
      let checkedKeys = this.$refs.menu.getCheckedNodes(); // 目前被选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys(); // 半选中的菜单节点
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys.menuId);
       let arr = []
      checkedKeys.map(item => {
        arr.push(item.menuId)
      })
      arr = arr.concat(halfCheckedKeys)

      return arr; 
      // return arr;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        // if (this.isExpand == true) {
        //   this.isExpand = false
        // } else {
        //   this.isExpand = true
        // }
        this.isExpand = !this.isExpand
      const nodes = this.$refs.menu.store._getAllNodes()
      for (let i in nodes) {
        nodes[i].expanded = this.isExpand
      }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        const treeInstance = this.$refs.menu;
        const rootNode = treeInstance.root;
        this.$refs.menu.setCheckedNodes(value ?this.traverseAndSelect(rootNode): []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    traverseAndSelect(node) {
      // 递归遍历节点并选择
      if (node.childNodes && node.childNodes.length > 0) {
        node.setChecked(true, false); // 第二个参数表示是否触发勾选事件
        node.childNodes.forEach(childNode => {
          this.traverseAndSelect(childNode);
        });
      } else {
        node.setChecked(true, false);
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.act = this.getMenuAllCheckedKeys();
            const { data: res } = await this.$http.post('/sys-role/saveOrUpdate', this.form)
            if (res.code === 20000) {
              this.$message.success(`修改成功!`)
              this.getList()
              this.dialogVisible = false
            } else {
              this.$message.error(res.msg)
            }
          } else {
            this.form.act = this.getMenuAllCheckedKeys();
            const { data: res } = await this.$http.post('/sys-role/saveOrUpdate', this.form)
            console.log(res,'123213123');
            if (res.code === 20000) {
              this.$message.success(`新增成功,请填写数据权限表!`)
              this.getList()
              this.dialogVisible = false
              this.$refs.form.resetFields()
              this.newRowid = res.data.roleId
              this.dataRouleHander(res.data)
              this.isClose = true  //让数据权限表无法关闭
            } else {
              this.$message.error(res.msg)
              this.$refs.form.resetFields()
            }
          }
        }
      });
    },

    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      this.form.dataScope = value
      if (value !== '2') {
        console.log(value);
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 提交按钮（数据权限） */
    submitDataScope: async function () {
      const newArr = this.newdataScopeList.map(obj => {
        const matchingObject = this.dataScopeList.find(item => item.uri === obj.uri);
        return matchingObject ? { ...obj, dataScope: matchingObject.dataScope } : obj;
      });
      const newArray = newArr.concat(this.dataScopeList.filter(obj => !this.newdataScopeList.some(item => item.uri === obj.uri)));
      const param = {
        roleKey: this.roleKey,
        scopes: newArray
      }
      let boolen = true
      newArray.forEach(item=>{
        if(item.dataScope==="2"&&!('depIds' in item)){
          this.$message.error('请选择组织');
          boolen = false
        }
      })
      if( boolen === false){
        return
      }
      const { data: res } = await this.$http.post(`/sys-role-scope-dtp/save`, param)
      if (res.code === 20000) {
        this.openDataScope = false;
        this.getList();
        this.condition=''
        if(this.isClose){
          this.$message.success('保存成功,是否现在分配用户')
          this.$router.push({ path: '/userRoule', query: { roleId: this.newRowid} })
          this.newRowid = ''
        }else{
          this.$message.success('保存成功')
          this.isClose = false
        }
      } else {
        this.$message.error(res.msg)
      }
    },

    // 取消按钮（数据权限）
    cancelDataScope() {
      if(this.isClose){
        this.$message.error('请填写数据权限表')
      }else{
         this.openDataScope = false;
         this.condition=''
      }
    },
    openCustom(){
      // var ids = this.$refs.tree.getCheckedKeys(false);
      //只选择叶子节点
      var leafIds = this.$refs.tree.getCheckedKeys(true);
      this.dataScopeList[this.treeindex].depIds=leafIds
      this.innerVisible=false
    },
    closedCustom(){
      this.innerVisible=false
      this.$refs.tree.setCheckedKeys([])

    },
    /** 查询菜单列表 */
    async getMenuList() {
      const { data: res } = await this.$http.get('/sys-menu/tree', { params: this.queryParams })
      if (res.code === 20000) {
        this.menuOptions = res.data
      }
    },
    handleSelectionChange(selection) {
      // 处理单条数据的选中状态
    },
    handleSelectAllA(val) {
      // 处理表头A的全选状态
      this.tableData.forEach(item => {
        item.A = val;
      });
    },
    handleSelectAllB(val) {
      // 处理表头B的全选状态
      this.tableData.forEach(item => {
        item.B = val;
      });
    },
  }
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.menuBox {
  width: 100%;
  height: 100%;
  border: 1px solid black;
}

.divStyle {
  width: 100px;
  height: 36px;
  border: 1px solid gray;
}
.dialog-table{
  width: 100%;
  height:400px;
  overflow-y: scroll;
  padding: 0;
  margin: 0;
  list-style: none;
  li{
    display: flex;
    justify-content: space-between;
    height: 30px;
    line-height: 30px;
    margin: 20px 10px;
  }
  .top-radio{
    display: flex;
    align-items: center;
    margin-left: 60px;
  }
}
</style>